﻿@{
    ViewData["Title"] = "UnitShow";
    Layout = "~/Views/Shared/Template.cshtml";
}

<h3>
    <span style="color:dodgerblue"></span>
    单位管理
</h3>
<hr>
<br />

<h4>数据筛选</h4>
<br />
<hr>
<div class="layui-form-item">
    <div class="layui-inline">
        <div class="layui-inline">
            <label class="layui-form-label">单位编号:</label>
            <div class="layui-input-block">
                <input type="text" id="unitNos" name="unitNo" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">单位名称:</label>
            <div class="layui-input-block">
                <input type="text" id="unitNames" name="unitName" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <button type="button" onclick="Show()" class="layui-btn layui-success">🔍搜索</button>
</div>
<hr>
<br />

<div style="float:right">
    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-bg-blue" lay-on="test-page-custom">
            <i class="layui-icon layui-icon-add-1"></i>新增
        </button>
        <button type="button" class="layui-btn layui-bg-blue" id="batchUpdBtn">
            <i class="layui-icon layui-icon-edit" id="editData"></i>编辑
        </button>
        <button type="button" class="layui-btn layui-bg-blue" id="batchDeleteButton">
            <i class="layui-icon layui-icon-delete"></i>删除
        </button>
        <button type="button" class="layui-btn layui-bg-blue" onclick="location.href='/Purchase/UnitShow'">
            <i class="layui-icon layui-icon-refresh"></i>刷新
        </button>
    </div>
</div>

<div style="padding: 20px;">
    <table class="layui-hide" id="UnitTable"></table>
    <script type="text/html" id="toolbarDemo"></script>
</div>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-bg-blue layui-btn-sm"><i class="layui-icon layui-icon-edit"></i>编辑</a>
    <a class="layui-btn layui-bg-red layui-btn-sm" ><i class="layui-icon layui-icon-delete" ></i>删除</a>
</script>

@* <table class="layui-table">
    <tr>
        <td><input type="checkbox" id="top" onclick="allSelect()" />全选/反选</td>
        <td>单位编号</td>
        <td>单位名称</td>
        <td>备注</td>
        <td>操作</td>
    </tr>
    <tbody id="tb"></tbody>
</table> *@
<div id="demo-laypage-all"></div>

<script>
    var obj = {

        unitId:'',
        unitNo: '',
        unitName: '',
        unitRemarks: '',
        office_id:'',
        user_id:'',
        createName: '',
        createTime: '',

    }
    var token = '';
    var pageIndex = 1;
    var pageSize = 100;
    var totalCount = 0;
    $(function () {
        // Page()
         Show()
    })
    function Show() {
    layui.use('table', function () {
        var table = layui.table;
        var laypage = layui.laypage;

        //查询
        var unitNo = $("#unitNos").val();
        var unitName = $("#unitNames").val();
        $.ajax({
                url: '/Purchase/GetUnitShow',
            async: false,
            type: "get",
            data: {
                unitNo: unitNo,
                unitName: unitName,
                pageIndex: pageIndex,
                    pageSize: pageSize,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res);
                console.log(res);
                    if (res.code == 0) {
                    console.log(res.data.list)
                    table.render({
                        elem: UnitTable,//对应HTML中表格的id
                        data: res.data.list,//绑定获取的数据
                        toolbar:'#toolbarDemo',
                        defaultToolbar:['exports'],
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'unitNo', title: '单位编号', width: 400 },
                            { field: 'unitName', title: '单位名称', width: 400 },
                            { field: 'unitRemarks', title: '备注', width: 400 },
                            {
                                field: '', title: '操作',width:450, templet: function (d) {
                                        return '<a class="layui-btn layui-btn-edit layui-btn-xs"  onclick="editData(' + d.unitId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                                            '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.unitId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                                }
                            }
                        ]],
                        page: true, // 是否显示分页
                        count: totalCount,
                        limits: [5, 10, 15],
                        limit: 5,// 每页默认显示的数量
                        curr: pageIndex,
                    });

                } else {
                    console.log(res.msg);
                }
                    totalCount = res.data.totalCount
                //console.log(totalCount)

            },
            error: function () {
                console.log("获取数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });
    });
}
  
    //添加弹框
    layui.use(function () {
        var $ = layui.$;
        var layer = layui.layer;
        var util = layui.util;
        var form = layui.form;
        // 事件
        util.on('lay-on', {
            'test-page-custom': function () {
                layer.open({
                    type: 1,
                    area: '800px',
                    resize: false,
                    shadeClose: true,
                    title: '新增供应商',
                    content: `<form class="layui-form layui-form-pane" action="" style="text-align: center;width:100%">

                             <div class="layui-form-item">
                                 <label class="layui-form-label">单位编号：</label>
                                 <div class="layui-input-inline">
                                    <input type="text" id="unitNo" name="unitNo" placeholder="可不填写,自动生成" autocomplete="off" class="layui-input"/>
                                 </div>
                                     <label class="layui-form-label">单位名称：</label>
                                     <div class="layui-input-inline">
                                               <input lay-verify="required" lay-reqtext="请填单位名称" type="text" id="unitName" name="unitName" autocomplete="off" class="layui-input"/>
                                     </div>
                                     
                                         <label class="layui-form-label">备注：</label>
                                         <div class="layui-input-inline">
                                                           <input lay-verify="required" lay-reqtext="请填备注" type="text" id="unitRemarks" name="unitRemarks" autocomplete="off" class="layui-input"/>
                                         </div>
                              </div>
                              <div class="layui-form-item">
                                 <button class="layui-btn" lay-submit lay-filter="demo-login">提交</button>
                                 <button type="reset" class="layui-btn layui-btn-primary">取消</button>
                             </div>
                         </form>`,
                    area: ['700px', '350px'],
                    success: function () {
                        // 对弹层中的表单进行初始化渲染
                        form.render();
                        // 表单提交事件
                        form.on('submit(demo-login)', function (data) {
                            var field = data.field; // 获取表单字段值
                            // 显示填写结果，仅作演示用

                            // 此处可执行 Ajax 等操作
                            // …
                            $.ajax({
                                url: '../Purchase/AddUnit',
                                type: 'post',
                                // contentType: 'application/json',
                                data: { data: JSON.stringify(field), token: localStorage.getItem("token") },
                                success: function (res) {
                                    var res = JSON.parse(res)
                                    console.log(field)
                                    console.log(res)

                                    if (res.code == 1) {
                                        layer.alert("添加成功");
                                        location.href = "/Purchase/UnitShow"
                                    }
                                    else {
                                        layer.alert("添加失败");
                                    }
                                }
                            })
                            return false; // 阻止默认 form 跳转
                        });
                    }
                });

                var n = new Date();
                var ss = n.getFullYear() + (n.getMonth() + 1).toString().padStart(2, '0') +
                    n.getDate().toString().padStart(2, '0') +
                    n.getHours().toString().padStart(2, '0') +
                    n.getMinutes().toString().padStart(2, '0') +
                    n.getSeconds().toString().padStart(2, '0');
                $("#unitNo").val(ss);
            }
        });



        window.editData = function (unitId) {
            // 先根据id获取要编辑的数据，发起Ajax请求
            $.ajax({
                type: "get",
                url: "/Purchase/GetFindUnit",  // 替换为实际的后台根据id获取数据的接口地址
                data: { unitId: unitId, token: localStorage.getItem("token") },
                //contentType: 'application/json',//浏览器里报415错
                success: function (res) {
                    console.log(res);
                    var res = JSON.parse(res)
                    console.log(res)
                    $(res.data).each(function () {
                        $('#unitId').val(this.unitId)
                        $('#unitNo').val(this.unitNo)
                        $('#unitName').val(this.unitName)
                        $('#unitRemarks').val(this.unitRemarks)
                        $('#office_id').val(this.office_id)
                        $('#user_id').val(this.user_id)
                        $('#createName').val(this.createName)
                        $('#createTime').val(this.createTime)
                        $('#updateName').val(this.updateName)
                        $('#updateTime').val(this.updateTime)

                        obj.unitId = this.unitId
                        obj.unitNo = this.unitNo
                        obj.unitName = this.unitName
                        obj.unitRemarks = this.unitRemarks
                        obj.office_id = this.office_id
                        obj.user_id = this.user_id
                        obj.createName = this.createName
                        obj.createTime = this.createTime

                    })
                },
            });

            layer.open({
                type: 1,
                title: '编辑承运商',
                content: `
                              <form class="layui-form layui-form-pane" action="" style="text-align: center;width:100%">

                              <div class="layui-form-item">
                                  <label class="layui-form-label">单位编号：</label>
                                  <div class="layui-input-inline">
                                     <input type="text" id="unitNo" name="unitNo" placeholder="可不填写,自动生成" autocomplete="off" class="layui-input"/>
                                  </div>
                                      <label class="layui-form-label">单位名称：</label>
                                      <div class="layui-input-inline">
                                        <input type="text" id="unitName" name="unitName" autocomplete="off" class="layui-input"/>
                                      </div>
                                          <label class="layui-form-label">备注：</label>
                                          <div class="layui-input-inline">
                                                    <input type="text" id="unitRemarks" name="unitRemarks" autocomplete="off" class="layui-input"/>
                                          </div>
                               </div>
                                   <input type="hidden" id="h2" name="Did" />
                               <div class="layui-form-item">
                                  <button class="layui-btn" lay-submit lay-filter="demo-login">提交</button>
                                  <button type="reset" class="layui-btn layui-btn-primary">取消</button>
                              </div>
                          </form>
                        `,
                area: ['700px', '400px'],
                success: function () {
                    var obj1 = {
                        unitId: '',
                        unitNo: '',
                        unitName: '',
                        unitRemarks: '',
                        office_id: '',
                        user_id: '',
                        createName: '',
                        createTime: '',
                        updateName: '',
                        updateTime: '',
                    };
                    // 对弹层中的表单进行初始化渲染
                    form.render();
                    // 表单提交事件
                    form.on('submit(demo-login)', function (data) {
                        var field = data.field;
                        obj1.unitId = obj.unitId
                        obj1.unitNo = field.unitNo
                        obj1.unitName = field.unitName
                        obj1.unitRemarks = field.unitRemarks
                        obj1.office_id = obj.office_id
                        obj1.user_id = obj.user_id
                        obj1.createName = obj.createName
                        obj1.createTime = obj.createTime
                        $.ajax({
                            url: '/Purchase/GetUpdateUnit',
                            type: 'post',
                           // contentType: 'application/json',
                            data: { obj1, token: localStorage.getItem("token") },
                            success: function (res) {
                                var list = JSON.parse(res)
                                console.log(field)
                                console.log(res)
                                if (list.data == 1) {
                                    layer.alert("修改成功");
                                    setTimeout(function () {
                                        location.reload();
                                    }, 2000);
                                }
                                else {
                                    layer.alert("修改失败");
                                }
                            }
                        })
                        return false; // 阻止默认 form 跳转
                    });
                }
            });
        };
       

    });

    
        //全选全不选
        function allSelect() {
            $(".ck").prop("checked", $("#top").prop("checked"));
        }
        //反选
        function isAll() {
            if ($(".ck").length == $(".ck:checked").length) {
                $("#top").prop("checked", true);
            }
            else {
                $("#top").prop("checked", false);
            }
        }
    window.deleteData = function (unitId) {
        var token = localStorage.getItem("token")
        var obj = JSON.stringify({
            "unitId": unitId
        })
        layer.confirm('确定要删除该条数据吗？', function (index) {
            $.ajax({
                type: "Post",
                url: "../Purchase/GetDeleteUnit",  // 替换为实际的后台删除数据接口地址
                data: { obj: obj, token: token },
                success: function (res) {
                    var res = JSON.parse(res)
                    if (res.code === 1) {
                        layer.alert("删除成功");
                        Show();  // 重新加载数据，刷新表格显示
                    } else {
                        layer.alert("删除失败");

                    }
                },
                error: function () {
                    layer.msg('删除失败，请稍后重试', {
                        time: 2000,
                        icon: 2
                    });
                }
            });
            layer.close(index);
        });
    };




    //产品批量删除
    $('#batchDeleteButton').click(function () {
        var table = layui.table;
        // 获取选中行的数据（这里主要是获取warehouseId）
        var checkStatus = table.checkStatus('UnitTable');
        var selectedData = checkStatus.data.map(function (item) {
            return item.unitId;
        });

        if (selectedData.length === 0) {
            layer.msg("请至少选择一条要删除的数据", { icon: 2 });
            return;
        }

        console.log(selectedData);
        layer.confirm('确定要批量删除选中的' + selectedData.length + '条数据吗？', function (index) {
            // 发送批量删除请求到后端
            $.ajax({
                url: "../Purchase/GetAllDeleteUnit", // 后端处理批量删除的接口地址，需根据实际情况调整
                type: "post",
                // contentType: "application/json",
                data: {
                    unitId: selectedData,
                    token: localStorage.getItem("token"),
                },
                success: function (res) {
                    var res = JSON.parse(res)
                    console.log(res);
                    if (res.data > 0) {
                        layer.msg("批量删除成功", { icon: 1 })
                        // 重新加载表格数据，展示更新后的列表
                        Show()
                    } else {
                        layer.msg("批量删除失败:" + res.message, { icon: 2 });
                    }
                },
                error: function () {
                    console.log("批量删除数据失败");
                    // 可以考虑显示一个错误消息给用户
                }
            });
        })
    })
//批量删除
    // 点击批量删除按钮的事件处理
    // $('#batchDeleteButton').click(function () {
    //     var table = layui.table;
    //     // 获取选中行的数据（这里主要是获取warehouseId）
    //     var checkStatus = table.checkStatus('UnitTable');
    //     var selectedData = checkStatus.data.map(function (item) {
    //         return Number(item.unitId);
    //     });

    //     if (selectedData.length === 0) {
    //         layer.msg("请至少选择一条要删除的数据", { icon: 2 });
    //         return;
    //     }

    //     console.log(selectedData);
    //     layer.confirm('确定要批量删除选中的' + selectedData.length + '条数据吗？', function (index) {
    //         var unitId = [];
    //         var model = {
    //             unitId: selectedData
    //         }
    //         console.log(model);
    //         // 发送批量删除请求到后端
    //         $.ajax({
    //             url: "/Purchase/GetAllDeleteUnit", // 后端处理批量删除的接口地址，需根据实际情况调整
    //             type: "post",
    //             // contentType: "application/json",
    //             data: {
    //                 model: model,
    //                 token: localStorage.getItem("token"),
    //             },
    //             success: function (res) {
    //                 var res = JSON.parse(res)
    //                 console.log(res.code);
    //                 if (res.code > 0) {
    //                     layer.msg("批量删除成功", { icon: 1 })
    //                     // 重新加载表格数据，展示更新后的列表
    //                     Show();
    //                 } else {
    //                     layer.msg("批量删除失败:" + res.message, { icon: 2 });
    //                 }
    //             },
    //             error: function () {
    //                 console.log("批量删除数据失败");
    //                 // 可以考虑显示一个错误消息给用户
    //             }
    //         });
    //     })
    // })







</script>




